package net.siufung.core.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

import java.beans.PropertyDescriptor;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 拷贝工具类(使用Spring BeansUtil)
 * @author 陈建峰
 * @since 2022/4/25 1:58 下午
 */
public class CopyUtil {

    /**
     * 全量拷贝
     * @param source 源
     * @param target 目标
     * @throws BeansException 拷贝异常
     */
    public static void copyProperties(Object source, Object target) throws BeansException {
        copyProperties(source, target, (String[]) null);
    }

    /**
     * 忽视值为Null属性拷贝
     * @param source 源
     * @param target 目标
     * @throws BeansException 拷贝异常
     */
    public static void copyPropertiesIgnoreNull(Object source, Object target) throws BeansException {
        copyProperties(source, target, getNullPropertyNames(source));
    }

    /**
     * 属性拷贝（带忽略属性参数）
     * @param source 源
     * @param target 目标
     * @param ignoreProperties 忽略属性
     * @throws BeansException 拷贝异常
     */
    public static void copyProperties(Object source, Object target, String... ignoreProperties) throws BeansException {
        // BeanUtils.copyProperties(source, target, ignoreProperties);
        BeanUtil.copyProperties(source, target, CopyOptions.create().setIgnoreProperties(ignoreProperties));
    }

    /**
     * 获取值为Null的属性名称集合
     * @param source 源
     * @return 值为Null的属性名称集合
     */
    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper beanWrapper = new BeanWrapperImpl(source);
        PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            Object propertyValue = beanWrapper.getPropertyValue(propertyDescriptor.getName());
            if (Objects.isNull(propertyValue)) {
                emptyNames.add(propertyDescriptor.getName());
            }
        }
        String[] propertyNames = new String[emptyNames.size()];
        return emptyNames.toArray(propertyNames);
    }

}
